package com.wx.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.wx.cache.SyncMap;
import com.wx.commons.SyncTagsFansThread;
import com.wx.core.process.WxApi;
import com.wx.entity.BatchTagsRequest;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxFansUser;
import com.wx.entity.WxTagJson;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxFansUserService;
import com.wx.util.HttpUtils;
import com.wx.util.JsonResult;
import com.wx.util.JsonUtil;
import com.zyht.bank.entity.AxdCustLoan;
import com.zyht.bank.entity.AxdCustLoanExample;
import com.zyht.bank.entity.WxTags;
import com.zyht.bank.entity.WxTagsExample;
import com.zyht.bank.service.AxdCustLoanService;
import com.zyht.bank.service.WxTagsService;
import com.zyht.bank.vo.WxFansVO;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.util.CommonUtils;
import com.zyht.common.util.Page;
import com.zyht.website.entity.SysUser;

@Controller
@RequestMapping("admin/tags")
public class WxTagsManagerController  extends AbsManageBaseController{
	
	@Resource
	private WxTagsService wxTagsService;
	
	@Resource
	private WxFansUserService wxFansUserService;
	
	@Resource
	private SysWxTokenService sysWxTokenService;
	
	@Resource
	private AxdCustLoanService axdCustLoanService;


	@Value("#{propertiesReader[session_user_key]}")
	private String sessionKey;
	@Value("#{propertiesReader[super_login_flag]}")
	private String sessionClouderlogin;
	
	private final String getTagsUrl = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=";
	
	private final String addTagsUrl = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=";
	
	private final String delTagsUrl = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=";
	
	private final String updateTagsUrl = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token=";
	
	private final String VIEW_PREFIX = "banks/manage/tags/";

	private final String makeView(String page) {
		return VIEW_PREFIX.concat(page);
	}

	/**
	* @author: John
	* @Title:  list
	* @Description: 标签列表页面
	* @param @param 
	* @return 
	* @throws
	*/ 
	@RequestMapping("list")
	public String list(HttpServletRequest req, HttpServletResponse res,
			Model model,Integer currentPage,String name){
		if(null == currentPage){
			currentPage = 1;
		}

		HttpSession session = req.getSession();
		Object sessionUser = session.getAttribute(sessionKey);

		if (sessionUser != null) {
			SysUser sysUser = (SysUser)sessionUser;
			int pageSize = getPageSize();
			PageHelper.startPage(currentPage,pageSize);
			List<WxTags> result;
			// 超管查询所有
	
			//	model.addAttribute("roleId", sysUser.getRoleId());
				WxTagsExample example = new WxTagsExample();
				if(StringUtils.hasText(name)){
					model.addAttribute("name", name);
					example.createCriteria().andTagNameLike("%"+name +"%"); // .andTagStatusEqualTo("1")
				}else{
					example.createCriteria(); // .andTagStatusEqualTo("1")
				}
				result = wxTagsService.list(example);
				for (WxTags wxTags : result) {
				List<AxdCustLoan> custLoan=	axdCustLoanService.findTags(wxTags.getTagId().toString());	
				wxTags.setTagCount(custLoan.size());
				wxTagsService.updateById(wxTags);
				}
				
			
			com.github.pagehelper.Page<WxTags> tags = (com.github.pagehelper.Page<WxTags>) result;
			Page<WxTags> page = new Page<WxTags>((int) tags.getTotal(),currentPage,
					pageSize);
			page.setRecordList(tags.getResult());
			model.addAttribute("page",page);
		}

		return makeView("list");
	}

	@Value("#{propertiesReader[session_wx_key]}")
	private String session_wx_key;

	@Resource
	private SysWxuserService sysWxuserService;

	/**
	* @author: John
	* @Title:  gett
	* @Description: 从微信获取公众号已创建的标签
	* @param @param 
	* @return 
	* @throws
	*/ 
	@RequestMapping("syn")
	public String syn(HttpServletRequest req, HttpServletResponse res, Model model){

		SysUser su = (SysUser) req.getSession().getAttribute("session_user");
		String threadName = "syncFansByTags" + su.getId();
		SyncTagsFansThread sysc = SyncMap.tagsFansMap.get(threadName);

		SysWxuser wxuser =null;
		String token = this.sysWxTokenService.getAccessToken(wxuser);
		String resultStr = HttpUtils.requestAsHttpGET(getTagsUrl+token);
		if(logger.isInfoEnabled()){
			logger.info("获取微信标签结果是："+resultStr);
		}
		
		// 根据  微信返回的数据更新或添加标签
		JSONObject json = JSON.parseObject(resultStr);
		List<WxTagJson> tagList = JSON.parseArray(json.get("tags").toString(), WxTagJson.class);

		// -------------------------------------------------------------------------------------------------------------
		// 同步标签下的粉丝
		if (CommonUtils.isNotEmpty(tagList)) {
			if (sysc == null || !sysc.isAlive()) {
				
				sysc = new SyncTagsFansThread();
				sysc.setName(threadName);
				SysWxuser sysWxuser =null;
				//SysWxuser sysWxuser = (SysWxuser) SessionUtil.getSessionObject(req, session_wx_key);
				sysWxuser.setId(su.getId());
				String accessToken = sysWxTokenService.getAccessToken(sysWxuser);
				if (StringUtils.isEmpty(accessToken)) {
					model.addAttribute("msg", "公众丢失授权绑定");
					model.addAttribute("redirect", "sysuser/list");
					return "message";
				}
				sysc.setAccessToken(accessToken);
				sysc.setSysWxuserService(sysWxuserService);
				sysc.setUid(su.getId());
				sysc.setWxFansUserService(wxFansUserService);
				sysc.setWxTagsService(wxTagsService);
				sysc.setWxid(sysWxuser.getWxid());

				sysc.setTagList(tagList);

				sysc.start();
				//SyncMap.tagsFansMap.put(threadName, sysc);
			}
		}
		
		model.addAttribute("msg", "同步微信标签中...");
		model.addAttribute("redirect", "admin/tags/list");
		return "tagsmeg";
	}
	
	@RequestMapping(value = "/syncCount", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	public @ResponseBody String syncCount(HttpServletRequest request) {
		SysUser su = (SysUser) request.getSession().getAttribute("session_user");
		String threadName = "syncFansByTags" + su.getId();
		SyncTagsFansThread sysc = SyncMap.tagsFansMap.get(threadName);

		if(sysc != null && sysc.isAlive()){
			HashMap<String ,Integer> map = new HashMap<String ,Integer>();
			map.put("total", sysc.getTotal());
			map.put("count", sysc.getCount());
			return JsonUtil.Object2Json(JsonResult.objectJson(map));
		}else{
			return JsonUtil.Object2Json(JsonResult.messageJson(false, ""));
		}
	}
	
	/**
	* @author: John
	* @Title:  addt
	* @Description: 创建标签
	* @param @param 
	* @return 
	* @throws
	*/ 
	@RequestMapping("addt")
	public@ResponseBody String addt(HttpServletRequest req, HttpServletResponse res,HttpSession session,
			Model model,String name, String lable){

		if (lable.equals("1")) {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			Map<String, Object> textMap = new HashMap<String, Object>();
			textMap.put("name",name);
			jsonMap.put("tag", textMap);
			String sessionWxKey = PropertiesUtils.getConfig("session_wx_key");
			SysWxuser wxuser = (SysWxuser) getSessionValue(session, sessionWxKey);
			String token = this.sysWxTokenService.getAccessToken(wxuser);
			try{
				String resultStr = HttpUtils.postHttpByJsonData(addTagsUrl+token, JSON.toJSONString(jsonMap));
				if(logger.isInfoEnabled())
					logger.info("添加标签结果是："+resultStr);
				JSONObject json = JSON.parseObject(resultStr);
				if(json.get("errcode") != null){
					String errcode = json.get("errcode").toString();
					if("45157".equals(errcode)){
						//重名
						return "name";
					}else if("45056".equals(errcode)){
						//创建不能超过100个
						return "out";
					}else{
						return "error";
					}
				}else{
					String tagStr = json.get("tag").toString();
					JSONObject tag = JSON.parseObject(tagStr);
					WxTags wxTags = new WxTags();
					wxTags.setTagId(Long.valueOf(tag.get("id").toString()));
					wxTags.setTagName(tag.get("name").toString());
					wxTags.setTagStatus("1");
					wxTags.setTagCount(0);
					this.wxTagsService.addOne(wxTags);
					return "success";
				}
			} catch (Exception e){
				e.printStackTrace();
				return "error";
			}
		} else {
			
			WxTagsExample ex = new WxTagsExample();
			ex.createCriteria().andTagNameEqualTo(name);
			
			int count = wxTagsService.count(ex);
			if (count > 0) {
				return "name";
			}
			
			
			WxTags wxTags = new WxTags();
			wxTags.setTagId(null);
			wxTags.setTagName(name);
			wxTags.setTagStatus("0");
			wxTags.setTagCount(0);
			this.wxTagsService.addOne(wxTags);
			return "success";
		}

	}
	
	/**
	* @author: John
	* @Title:  delt
	* @Description: 删除标签
	* @param @param 
	* @return 
	* @throws
	*/ 
	@RequestMapping("delt")
	public String deleteTags(HttpServletRequest req, Long id, String tagStatus,HttpSession session){

		WxTags tagInfo = wxTagsService.findOneById(id.intValue());

		if ("1".equals(tagStatus)) {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			Map<String, Object> textMap = new HashMap<String, Object>();
			textMap.put("id",tagInfo.getTagId());
			jsonMap.put("tag", textMap);
			String sessionWxKey = PropertiesUtils.getConfig("session_wx_key");
			SysWxuser wxuser = (SysWxuser) getSessionValue(session, sessionWxKey);
			String token = this.sysWxTokenService.getAccessToken(wxuser);
			try{
				String resultStr = HttpUtils.postHttpByJsonData(delTagsUrl+token, JSON.toJSONString(jsonMap));
				if(logger.isInfoEnabled())
					logger.info("删除标签结果是："+resultStr);
				JSONObject json = JSON.parseObject(resultStr);
				String errcode = json.get("errcode").toString();
				String errmsg = json.get("errmsg").toString();
				if("0".equals(errcode) && "ok".equals(errmsg)){
					wxTagsService.deleteById(id.intValue());
				}

			} catch (Exception e){
				e.printStackTrace();
			}
		} else {
			wxTagsService.deleteById(id.intValue());
		}
		
		
		if ("1".equals(tagStatus)) {
			//List<WxFansUser> list = wxFansUserService.queryFansInfoByTagId(tagInfo.getTagId().toString());
			AxdCustLoanExample loan = new AxdCustLoanExample();
			loan.createCriteria().andFlagEqualTo(tagInfo.getTagId().toString());
			List<AxdCustLoan> list = axdCustLoanService.list(loan);
			for (AxdCustLoan info : list) {
				List<String> tagsList = CommonUtils.parseList(info.getFlag());
				// 粉丝移除所包含的标签
				tagsList.remove(tagInfo.getTagId().toString());
				
				if (CommonUtils.isNotEmpty(tagsList)) {
					info.setFlag("," + org.apache.commons.lang.StringUtils.join(tagsList, ",") + ",");
				} else {
					info.setFlag(null);
				}
				
				// 更新本地数据库
				axdCustLoanService.updateById(info);
			}
		} 

		return "redirect:list";
	}
	
	
	/**
	* @author: John
	* @Title:  addt
	* @Description: 编辑标签
	* @param @param 
	* @return 
	* @throws
	*/ 
	@RequestMapping("edit")
	public@ResponseBody String edit(HttpServletRequest req, Long id, String name,HttpSession session){

		WxTags tagInfo = wxTagsService.findOneById(id.intValue());

		String tagStatus = tagInfo.getTagStatus();

		if ("1".equals(tagStatus)) {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			Map<String, Object> textMap = new HashMap<String, Object>();
			textMap.put("id",tagInfo.getTagId());
			textMap.put("name",name);
			jsonMap.put("tag", textMap);
			String sessionWxKey = PropertiesUtils.getConfig("session_wx_key");
			SysWxuser wxuser = (SysWxuser) getSessionValue(session, sessionWxKey);
			String token = this.sysWxTokenService.getAccessToken(wxuser);
			try{
				String resultStr = HttpUtils.postHttpByJsonData(updateTagsUrl+token, JSON.toJSONString(jsonMap));
				if(logger.isInfoEnabled())
					logger.info("修改标签结果是："+resultStr);
				JSONObject json = JSON.parseObject(resultStr);
				String errcode = json.get("errcode").toString();
				String errmsg = json.get("errmsg").toString();
				if("0".equals(errcode) && "ok".equals(errmsg)){
					tagInfo.setTagName(name);
					this.wxTagsService.updateById(tagInfo);
					return "success";
				}else if("45157".equals(errcode)){
					//重名
					return "name";
				}
			} catch (Exception e){
				e.printStackTrace();
				return "error";
			}
		} else {
			tagInfo.setTagName(name);
			this.wxTagsService.updateById(tagInfo);
			return "success";
		}

		return "error";
	}
	
	/**
	 * <b>作者:</b> Bob<br/>
	 * <b>修改时间：</b>2016年12月2日 - 上午11:14:27<br/>
	 * <b>功能说明：</b>选择粉丝<br/>
	 * @param tagId
	 * @param nickName
	 * @param model
	 * @return
	 */
	@RequestMapping(value="fans", method=RequestMethod.GET)
	public String chooseFans(@RequestParam("t") Integer tagId, Model model){
		model.addAttribute("tagId",tagId);
		return makeView("chooseFans");
	}
	
	/**
	 * <b>作者:</b> Bob<br/>
	 * <b>修改时间：</b>2016年12月2日 - 下午2:46:42<br/>
	 * <b>功能说明：</b>	<br/>
	 * @param nickName
	 * @param Model 
	 */
		
	@RequestMapping(value="fans", method=RequestMethod.POST)
	public void doChooseFans(String nickName, HttpServletResponse response, Model model){
		if(!StringUtils.isEmpty(nickName)){
			List<WxFansVO> list = this.wxTagsService.getFansInfo(nickName);
			String json = JSON.toJSONString(list);
			writeJson(response,json);
		}
	}
	
	@RequestMapping(value="batch", method=RequestMethod.POST)
	public void bindTags(String ids, Integer tagId, HttpServletRequest request, HttpServletResponse response,HttpSession session){
		BatchTagsRequest param = new BatchTagsRequest();
		param.setTagid(tagId);
		JSONObject result = new JSONObject();
		if(!StringUtils.isEmpty(ids)){
			List<Integer> list = new ArrayList<Integer>();
			String[] idArray = ids.split(",");
			for(String idstr : idArray){
				if(!StringUtils.isEmpty(idstr)){
					Integer id = Integer.parseInt(idstr);
					if(!list.contains(id))
						list.add(id);
				}
			}
			if(list.size()>0){
				List<String> openidList = this.wxTagsService.getOpenIds(list);
				param.setOpenidList(openidList);
				
				String json = JSON.toJSONString(param);
				String sessionWxKey = PropertiesUtils.getConfig("session_wx_key");
				SysWxuser wxuser = (SysWxuser) getSessionValue(session, sessionWxKey);
				String token = this.sysWxTokenService.getAccessToken(wxuser);
				try{
					String resultStr = HttpUtils.postHttpByJsonData(WxApi.BATCH_TAGGING_URL+token, json);
					JSONObject jsonResult = JSON.parseObject(resultStr);
					Integer errcode = jsonResult.getInteger("errcode");
					if(0==errcode){
						result.put("state",200);
					}else{
						result.put("state",405);
						result.put("msg","打标签失败："+jsonResult.getString("errmsg"));
					}
				} catch (IOException e){
					e.printStackTrace();
					result.put("state",501);
					result.put("msg","网络异常");
				}
				
			}else{
				result.put("state",401);
				result.put("msg","粉丝信息不能空");
			}
		}else{
			result.put("state",401);
			result.put("msg","粉丝信息不能空");
		}
		writeJson(response,result.toJSONString());
	}
	
	
	@RequestMapping("conversion/{type}/{id}")
	public@ResponseBody String conversion(HttpServletRequest req, HttpServletResponse res,
			 HttpSession session,
			Model model, @PathVariable("type") String type, @PathVariable("id") Long id){
		
		if (CommonUtils.isNotEmpty(type) && CommonUtils.isNotEmpty(id)) {
			
			WxTags info = wxTagsService.findOneById(id.intValue());
			String sessionWxKey = PropertiesUtils.getConfig("session_wx_key");
			SysWxuser wxuser = (SysWxuser) getSessionValue(session, sessionWxKey);
			String token = this.sysWxTokenService.getAccessToken(wxuser);

			Map<String, Object> jsonMap = new HashMap<String, Object>();
			Map<String, Object> textMap = new HashMap<String, Object>();
			// 转换到微信
			if (type.equals("wechat")) {
				// 添加到微信端标签
				textMap.put("name",info.getTagName());
				jsonMap.put("tag", textMap);
				try{
					String resultStr = HttpUtils.postHttpByJsonData(addTagsUrl+token, JSON.toJSONString(jsonMap));
					if(logger.isInfoEnabled()) {
						logger.info("添加标签结果是："+resultStr);
					}
						
					JSONObject json = JSON.parseObject(resultStr);
					if(json.get("errcode") != null){
						String errcode = json.get("errcode").toString();
						if("45157".equals(errcode)){
							//重名
							return "name";
						}else if("45056".equals(errcode)){
							//创建不能超过100个
							return "out";
						}else{
							return "error";
						}
					}else{
						String tagStr = json.get("tag").toString();
						JSONObject tag = JSON.parseObject(tagStr);
						info.setTagId(Long.valueOf(tag.get("id").toString()));
						info.setTagStatus("1");
						info.setTagCount(0);
						
//						wxTagsService.updateById(info);
						//同时更新粉丝 local_tag, tags 字段, 放入一个事务
						wxTagsService.updateTagsInfo(info, id.toString());
						return "success";
					}
				} catch (Exception e){
					e.printStackTrace();
					return "error";
				}
				
			}
			// 转换到本地
			else if (type.equals("local")) {
				String wxTag = info.getTagId().toString();
				if(info != null) {
					// 删除微信端标签
					textMap.put("id",info.getTagId());
					jsonMap.put("tag", textMap);
					
					String resultStr = null;
					try {
						resultStr = HttpUtils.postHttpByJsonData(delTagsUrl+token, JSON.toJSONString(jsonMap));
					} catch (IOException e) {
						e.printStackTrace();
					}
					
					if(logger.isInfoEnabled()){
						logger.info("删除标签结果是："+resultStr);
					}
					
					// 数据库更新标签状态0
					JSONObject json = JSON.parseObject(resultStr);
					String errcode = json.get("errcode").toString();
					String errmsg = json.get("errmsg").toString();
					if("0".equals(errcode) && "ok".equals(errmsg)){
						info.setTagStatus("0");
						info.setTagCount(0);
						info.setTagId(null);
						
//						wxTagsService.updateById(info);
						wxTagsService.updateLocalTagsInfo(info, id.toString(), wxTag);
						return "success";
					}
				}
			}
		}
		
		return "error";
	}
	
	
	
	/**
	 * <b>作者:</b> Bob<br/>
	 * <b>修改时间：</b>2016年12月2日 - 下午2:46:42<br/>
	 * <b>功能说明：</b>	<br/>
	 * @param 根据标签查找客户
	 * @param Model 
	 */
		
	@RequestMapping(value="cust", method=RequestMethod.GET)
	public String cust(String nickName, HttpServletResponse response, Model model,String localId,Integer currentPage){
		
		if(null == currentPage){
			currentPage = 1;
		}
		int pageSize = getPageSize();
		PageHelper.startPage(currentPage,pageSize);
		if(!StringUtils.isEmpty(localId)){
			 
			 List<AxdCustLoan> tagsList= axdCustLoanService.findTags(localId);
			 if(tagsList.size()>0){
				 com.github.pagehelper.Page<AxdCustLoan> tags = (com.github.pagehelper.Page<AxdCustLoan>) tagsList;
					Page<AxdCustLoan> page = new Page<AxdCustLoan>((int) tags.getTotal(),currentPage,
							pageSize);
					page.setRecordList(tags.getResult());
					model.addAttribute("page",page);
			 }
		}
		return makeView("cust");
		
	}
	
}
	

